<template>
  <div class="chart-card">
    <div id="pie-main" class="pie-main"></div>
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue';
  import * as echarts from 'echarts';
  const emit = defineEmits(['detail']);

  import { iotApi as iotBoxApi } from '/@/api/plat/collectBox';
  import { iotApi as iotDeviceApi } from '/@/api/plat/southDevice';

  let centerInfo = {
    type: 'center',
    name: '船岸协同辅助系统',
    version: '1.0.1',
    box: 0,
    device: 0,
    children: [],
  };

  // 转换函数：将树形数据转成nodes和edges格式
  function convertTreeDataToGraphData(treeData) {
    const nodes = [];
    const edges = [];

    const rootX = 400;
    const rootY = 50;
    const boxY = 150;
    const boxSpacing = 300;
    const deviceSpacing = 150;

    if (!treeData || treeData.length === 0) return { nodes, edges };

    const root = treeData[0];

    // 根节点
    nodes.push({
      id: 'root',
      name: root.name,
      x: rootX,
      y: rootY,
      symbol: 'roundRect',
      symbolSize: [180, 60],
      itemStyle: {
        color: '#FFBA00',
        borderRadius: 12,
        shadowColor: 'rgba(0,0,0,0.2)',
        shadowBlur: 10,
      },
      label: {
        fontSize: 18,
        color: '#fff',
        fontWeight: 'bold',
      },
      isOnline: true,
      params: root,
    });

    root.children.forEach((box, boxIndex) => {
      const boxX = rootX - boxSpacing / 2 + boxIndex * boxSpacing;

      nodes.push({
        id: `box${boxIndex}`,
        name: box.name,
        x: boxX,
        y: boxY,
        symbol: 'roundRect',
        symbolSize: [120, 50],
        itemStyle: {
          color: box.state ? '#34c38f' : '#888',
          borderRadius: 8,
        },
        label: {
          color: '#fff',
          fontSize: 14,
        },
        isOnline: box.state,
        params: box,
      });

      edges.push({
        source: 'root',
        target: `box${boxIndex}`,
        lineStyle: {
          color: box.state ? '#00D38D' : '#f00',
          width: 2,
          type: box.state ? 'solid' : 'dashed',
        },
      });
    });
    const deviceSpacingX = 100;
    let deviceCounter = 0;
    const deviceHeight = 140;
    const deviceWidth = 35;

    root.children.forEach((box, boxIndex) => {
      const boxNode = nodes.find((n) => n.id === `box${boxIndex}`);
      const boxX = boxNode ? boxNode.x : 0;
      box.children.forEach((device, deviceIndex) => {
        const deviceX = 100 + deviceCounter * deviceSpacingX;
        // 这里的 deviceY 不变（比如 350）
        const deviceY = 350;
        const adjustedDeviceY = deviceY + -30; // 上移75%高度

        // 将设备名每个字符换一行（竖排显示）
        const verticalName = device.name.split('').join('\n');

        nodes.push({
          id: `device${boxIndex}_${deviceIndex}`,
          name: verticalName,
          x: deviceX,
          y: adjustedDeviceY,
          symbolSize: [35, deviceHeight],
          symbol: 'roundRect',
          itemStyle: {
            color: device.state ? '#ddefff' : '#ffe0e0',
            borderRadius: 6,
          },
          label: {
            position: 'inside',
            fontSize: 12,
            color: '#333',
            lineHeight: 16,
          },
          isOnline: device.state,
          params: device,
        });

        nodes.push({
          id: `anchor${boxIndex}_${deviceIndex}`,
          x: deviceX,
          y: deviceY - 100, // 设备顶部位置
          symbolSize: [1, 1],
          symbol: 'circle',
          itemStyle: { color: 'transparent' },
          label: { show: false },
          silent: true,
        });

        edges.push({
          source: `box${boxIndex}`,
          target: `anchor${boxIndex}_${deviceIndex}`,
          lineStyle: {
            color: device.state ? '#00D38D' : '#f00',
            width: 2,
            type: device.state ? 'solid' : 'dashed',
            curveness: deviceX < boxX ? -0.3 : 0.3,
          },
          params: device,
        });

        deviceCounter++;
      });
    });

    return { nodes, edges };
  }

  function initChart(list) {
    const { nodes, edges } = convertTreeDataToGraphData(list);

    const option = {
      backgroundColor: '#f9f9f9',
      series: [
        {
          type: 'graph',
          layout: 'none',
          data: nodes,
          links: edges,
          edgeSymbol: ['none', 'arrow'],
          symbolKeepAspect: true,
          roam: false,
          label: {
            show: true,
          },
          lineStyle: {
            opacity: 1,
          },
        },
      ],
    };

    const chartDom = document.getElementById('pie-main');
    if (chartDom) {
      const myChart = echarts.init(chartDom);
      myChart.setOption(option);

      myChart.on('click', function (params) {
        if (params.dataType === 'node') {
          const row = params.data.params;
          emit('detail', row);
        }
      });
    }
  }
  function getBoxList() {
    iotBoxApi.queryList().then(({ data }) => {
      const list = data.map((m, i) => {
        return Object.assign({}, m, {
          index: i,
          id: m.boxId,
          type: 'box',
          name: m.boxName,
          state: m.boxId === 5718331248218112,
          children: [],
        });
      });
      getDeviceList(list);
    });
  }
  function getDeviceList(list) {
    iotDeviceApi.queryList().then(({ data }) => {
      let obj = {};
      for (let item of list) {
        obj[item.id] = item;
      }
      for (let item of data) {
        if (obj[item.boxId]) {
          const index = obj[item.boxId].index;
          list[index].children.push(
            Object.assign({}, item, {
              id: item.deviceId,
              name: item.deviceName,
              state: item.deviceId === 5748950103625728 || item.deviceId === 9754606448021504,
              type: 'device',
            })
          );
        }
      }
      centerInfo.box = list.length;
      centerInfo.device = data.length;
      centerInfo.children = list;
      initChart([centerInfo]);
      emit('detail', centerInfo);
    });
  }

  onMounted(getBoxList);
</script>

<style scoped lang="less">
  .chart-card {
    width: 100%;
    height: 500px;
    display: flex;
    align-items: center;
    justify-content: center;

    .pie-main {
      width: 100%;
      height: 100%;
      background: #fff;
    }
  }
</style>
